package com.java.netty.nio.netty.tcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * @Author: Dgg
 * @Date: 2022/1/24 22:05
 */
public class MyClinetHandler extends SimpleChannelInboundHandler<ByteBuf> {
	private int count;

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {

		byte[] buff = new byte[msg.readableBytes()];
		msg.readBytes(buff);

		String s = new String(buff, CharsetUtil.UTF_8);
		System.out.println("客户端接收到消息 = " + s);
		System.out.println("客户端接受数量 = " + (++this.count));
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		//使用客户端 发送十次数据
		for (int i = 0; i < 10; i++) {
			ByteBuf byteBuf = Unpooled.copiedBuffer("hello Server" + i, CharsetUtil.UTF_8);
			ctx.writeAndFlush(byteBuf);
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}
}
